package it.unibo.deis.lia.mmhc;

import it.unibo.deis.lia.mmhc.sfm.ClientServiceSearch;
import it.unibo.deis.lia.mmhc.sfm.FindedService;
import it.unibo.deis.lia.mmhc.spm.LocalService;
import it.unibo.deis.lia.mmhc.spm.Service;
import it.unibo.deis.lia.mmhc.spm.ServiceManager;
import it.unibo.deis.lia.servicemmhc.clock.ClientClock;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;

import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Leading;

//VS4E -- DO NOT REMOVE THIS LINE!
public class ServiceGui extends JFrame implements Runnable {

	private static final long serialVersionUID = 1L;
	private JButton jButton0;
	private JTextField jTextField0;
	private JSpinner jSpinner0;
	private JTextField jTextField1;
	private JButton jButton1;
	private JTextField jTextField2;
	private JSeparator jSeparator0;
	private JSeparator jSeparator1;
	private static JList jList0;
	private JScrollPane jScrollPane0;
	private JLabel jLabel0;
	private JButton jButton2;
	private JSeparator jSeparator2;
	private JLabel jLabel1;
	private JList jList1;
	private JScrollPane jScrollPane1;
	private static DefaultListModel listTrovati;
	private DefaultListModel listAttivi;
	private static Vector<FindedService> findedService;
	private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";

	public ServiceGui() {
		initComponents();
	}

	private void initComponents() {
		setTitle("ServiceMMHC");
		setResizable(false);
		setLayout(new GroupLayout());
		add(getJButton0(), new Constraints(new Leading(151, 10, 10),
				new Leading(9, 12, 12)));
		add(getJTextField0(), new Constraints(new Leading(12, 91, 12, 12),
				new Leading(12, 12, 12)));
		add(getJButton1(), new Constraints(new Leading(161, 10, 10),
				new Leading(50, 12, 12)));
		add(getJSpinner0(), new Constraints(new Leading(105, 38, 10, 10),
				new Leading(12, 12, 12)));
		add(getJSeparator0(), new Constraints(new Leading(-7, 239, 10, 10),
				new Leading(43, 5, 12, 12)));
		add(getJTextField1(), new Constraints(new Leading(4, 89, 12, 12),
				new Leading(52, 12, 12)));
		add(getJTextField2(), new Constraints(new Leading(103, 48, 10, 10),
				new Leading(52, 12, 12)));
		add(getJSeparator1(), new Constraints(new Leading(-5, 235, 12, 12),
				new Leading(81, 10, 12, 12)));
		add(getJLabel0(), new Constraints(new Leading(20, 10, 10), new Leading(
				93, 12, 12)));
		add(getJButton2(), new Constraints(new Leading(12, 213, 12, 12),
				new Leading(194, 10, 10)));
		add(getJSeparator2(), new Constraints(new Leading(0, 245, 12, 12),
				new Leading(225, 10, 12, 12)));
		add(getJScrollPane0(), new Constraints(new Leading(11, 214, 12, 12),
				new Leading(109, 82, 12, 12)));
		add(getJLabel1(), new Constraints(new Leading(12, 12, 12), new Leading(
				231, 12, 12)));
		add(getJScrollPane1(), new Constraints(new Leading(13, 210, 12, 12),
				new Leading(252, 50, 10, 10)));
		setSize(242, 312);
	}

	private JScrollPane getJScrollPane1() {
		if (jScrollPane1 == null) {
			jScrollPane1 = new JScrollPane();
			jScrollPane1.setViewportView(getJList1());
		}
		return jScrollPane1;
	}

	private JList getJList1() {
		if (jList1 == null) {
			jList1 = new JList();
			listAttivi = new DefaultListModel();
			listAttivi.addElement("Nessun servizio attivato");
			jList1.setModel(listAttivi);
		}
		return jList1;
	}

	private JLabel getJLabel1() {
		if (jLabel1 == null) {
			jLabel1 = new JLabel();
			jLabel1.setText("Servizi Attivati");
		}
		return jLabel1;
	}

	private JSeparator getJSeparator2() {
		if (jSeparator2 == null) {
			jSeparator2 = new JSeparator();
		}
		return jSeparator2;
	}

	private JButton getJButton2() {
		if (jButton2 == null) {
			jButton2 = new JButton();
			jButton2.setText("Attiva");
			jButton2.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent event) {
					jButton2MouseMouseClicked(event);
				}
			});
		}
		return jButton2;
	}

	private JLabel getJLabel0() {
		if (jLabel0 == null) {
			jLabel0 = new JLabel();
			jLabel0.setText("Servizi trovati");
		}
		return jLabel0;
	}

	private JScrollPane getJScrollPane0() {
		if (jScrollPane0 == null) {
			jScrollPane0 = new JScrollPane();
			jScrollPane0.setViewportView(getJList0());
		}
		return jScrollPane0;
	}

	private JList getJList0() {
		if (jList0 == null) {
			jList0 = new JList();
			listTrovati = new DefaultListModel();
			listTrovati.addElement("Nessun servizio trovato");
			jList0.setModel(listTrovati);
		}
		return jList0;
	}

	private JSeparator getJSeparator1() {
		if (jSeparator1 == null) {
			jSeparator1 = new JSeparator();
		}
		return jSeparator1;
	}

	private JSeparator getJSeparator0() {
		if (jSeparator0 == null) {
			jSeparator0 = new JSeparator();
		}
		return jSeparator0;
	}

	private JTextField getJTextField2() {
		if (jTextField2 == null) {
			jTextField2 = new JTextField();
			jTextField2.setText("3000");
		}
		return jTextField2;
	}

	private JButton getJButton1() {
		if (jButton1 == null) {
			jButton1 = new JButton();
			jButton1.setText("Add");
			jButton1.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent event) {
					jButton1MouseMouseClicked(event);
				}
			});
		}
		return jButton1;
	}

	private JTextField getJTextField1() {
		if (jTextField1 == null) {
			jTextField1 = new JTextField();
			jTextField1.setText("clock");
		}
		return jTextField1;
	}

	private JSpinner getJSpinner0() {
		if (jSpinner0 == null) {
			jSpinner0 = new JSpinner();
			SpinnerNumberModel model = new SpinnerNumberModel();
			model.setValue(1);
			jSpinner0.setModel(model);

		}
		return jSpinner0;
	}

	private JTextField getJTextField0() {
		if (jTextField0 == null) {
			jTextField0 = new JTextField();
			jTextField0.setText("clock");
		}
		return jTextField0;
	}

	private JButton getJButton0() {
		if (jButton0 == null) {
			jButton0 = new JButton();
			jButton0.setText("Search");
			jButton0.addMouseListener(new MouseAdapter() {

				public void mouseClicked(MouseEvent event) {
					jButton0MouseMouseClicked(event);
				}
			});
		}
		return jButton0;
	}

	private static void installLnF() {
		try {
			String lnfClassname = PREFERRED_LOOK_AND_FEEL;
			if (lnfClassname == null)
				lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
			UIManager.setLookAndFeel(lnfClassname);
		} catch (Exception e) {
			System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
					+ " on this platform:" + e.getMessage());
		}
	}

	/**
	 * Main entry of the class. Note: This class is only created so that you can
	 * easily preview the result at runtime. It is not expected to be managed by
	 * the designer. You can modify it as you like.
	 */

	public void run() {
		installLnF();
		findedService = new Vector<FindedService>();
		ServiceGui frame = new ServiceGui();
		frame.setDefaultCloseOperation(ServiceGui.EXIT_ON_CLOSE);
		frame.setTitle("ServiceGui");
		frame.getContentPane().setPreferredSize(frame.getSize());
		frame.pack();
		// frame.setLocationRelativeTo(null);
		frame.setLocation(50, 300);
		frame.setVisible(true);
		 frame.addWindowListener(new WindowAdapter() {
		        public void windowClosing(WindowEvent event) {
		        	try{
		        		Process k3 = Runtime.getRuntime().exec("sh dis.sh");
		        	
		    		k3.waitFor();
		    		k3.destroy();
		            }
		        	catch (Exception e) {
						// TODO: handle exception
					}
		        }
		    });

	}

	private void jButton0MouseMouseClicked(MouseEvent event) {
		int numberHop = (Integer) jSpinner0.getValue();
		if (numberHop < 1)
			numberHop = 0;
		ClientServiceSearch search = new ClientServiceSearch(jTextField0
				.getText(), numberHop);
		search.start();
	}

	private void jButton1MouseMouseClicked(MouseEvent event) {
		LocalService.getInstance().addServizio(jTextField1.getText(),
				Integer.parseInt(jTextField2.getText()));
		if (listAttivi.contains("Nessun servizio attivato"))
			listAttivi.clear();
		listAttivi.addElement(jTextField1.getText() + " "
				+ jTextField2.getText() + " proprietà");
		jList1.setModel(listAttivi);
	}

	private void jButton2MouseMouseClicked(MouseEvent event) {
		String selected = (String) jList0.getSelectedValue();
		String[] sel = selected.split(" ");
		String fornitore = sel[0];
		String nome = sel[1];
		int porta = Integer.parseInt(sel[2]);
		for (int i = 0; i < findedService.size(); i++) {
			Service servi = (Service) findedService.elementAt(i).getOgg();
			if (servi.getFornitore().equalsIgnoreCase(fornitore)
					&& servi.getName().equalsIgnoreCase(nome)
					&& servi.getPort() == porta) {
				try {
					ServiceManager.getInstance().serviceAttivation(
							findedService.elementAt(i));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				parserClientServer(servi.getName(), servi.getPort());
			}

		}
	}

	public static void addFindedService(FindedService service) {
		if (!contain(findedService, service)) {
			findedService.add(service);
			if (listTrovati.contains("Nessun servizio trovato"))
				listTrovati.clear();

			listTrovati.addElement(((Service) service.getOgg()).getFornitore()
					+ " " + ((Service) service.getOgg()).getName() + " "
					+ ((Service) service.getOgg()).getPort());
			jList0.setModel(listTrovati);
		}
	}

	private static boolean contain(Vector<FindedService> findedService2,
			FindedService service) {
		Service serv = (Service) service.getOgg();
		for (int i = 0; i < findedService2.size(); i++) {
			Service servi = (Service) findedService2.elementAt(i).getOgg();
			if (servi.getFornitore().equalsIgnoreCase(serv.getFornitore())
					&& servi.getName().equalsIgnoreCase(serv.getName())
					&& servi.getPort() == serv.getPort())
				return true;
		}
		return false;
	}

	private void parserClientServer(String nome, int porta) {
		if (nome.equalsIgnoreCase("clock")) {
			ClientClock clock = new ClientClock(porta);
			clock.run();
		}
	}

}
